<template>
  <div class="svg-canvas-container">
    <div class="canvas-tools">
      <van-button-group>
        <van-button icon="zoom-in" size="small" @click="zoomIn" />
        <van-button icon="zoom-out" size="small" @click="zoomOut" />
        <van-button icon="replay" size="small" @click="resetZoom" />
      </van-button-group>
      <span class="zoom-level">{{ Math.round(editorStore.canvas.zoom * 100) }}%</span>
    </div>
    
    <div class="canvas-wrapper">
      <canvas ref="canvasRef" :width="canvasWidth" :height="canvasHeight"></canvas>
    </div>
    
    <div class="canvas-status">
      <van-checkbox v-model="showGrid">显示网格</van-checkbox>
      <van-checkbox v-model="showRulers">显示标尺</van-checkbox>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
import { fabric } from '@/utils/fabricWrapper';
import { useEditorStore, useSettingsStore } from '@/stores';
import { eventBus } from '@/utils/eventBus';

const canvasRef = ref<HTMLCanvasElement>();
const fabricCanvas = ref<fabric.Canvas>();

const editorStore = useEditorStore();
const settingsStore = useSettingsStore();

// 计算画布尺寸
const canvasWidth = computed(() => editorStore.canvas.width);
const canvasHeight = computed(() => editorStore.canvas.height);

// 网格和标尺显示状态
const showGrid = computed({
  get: () => editorStore.canvas.showGrid,
  set: (value) => editorStore.toggleGrid()
});

const showRulers = computed({
  get: () => editorStore.canvas.showRulers,
  set: (value) => editorStore.toggleRulers()
});

// 监听窗口大小变化
watch(() => [window.innerWidth, window.innerHeight], () => {
  resizeCanvas();
}, { flush: 'post' });

onMounted(() => {
  if (canvasRef.value) {
    // 初始化Fabric.js画布
    fabricCanvas.value = new fabric.Canvas(canvasRef.value, {
      width: canvasWidth.value,
      height: canvasHeight.value,
      backgroundColor: editorStore.canvas.backgroundColor,
      preserveObjectStacking: true,
      selection: true,
      defaultCursor: 'default',
      hoverCursor: 'move',
      stopContextMenu: true
    });

    // 设置画布事件监听
    setupCanvasEvents();
    
    // 发送画布初始化完成事件
    eventBus.emit('canvas:initialized', { canvas: fabricCanvas.value });
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', resizeCanvas);
  }
});

onUnmounted(() => {
  if (fabricCanvas.value) {
    fabricCanvas.value.dispose();
  }
  window.removeEventListener('resize', resizeCanvas);
});

function setupCanvasEvents() {
  if (!fabricCanvas.value) return;

  // 监听对象选择事件
  fabricCanvas.value.on('selection:created', (e) => {
    const activeObject = e.selected?.[0];
    if (activeObject) {
      eventBus.emit('element:selected', { 
        element: activeObject,
        elementId: activeObject.id || 'unknown'
      });
    }
  });

  // 监听对象取消选择事件
  fabricCanvas.value.on('selection:cleared', () => {
    eventBus.emit('element:deselected');
  });

  // 监听对象修改事件
  fabricCanvas.value.on('object:modified', (e) => {
    if (e.target) {
      eventBus.emit('element:modified', {
        element: e.target,
        elementId: e.target.id || 'unknown'
      });
    }
  });

  // 监听画布缩放事件
  fabricCanvas.value.on('mouse:wheel', (opt) => {
    const delta = opt.e.deltaY;
    let zoom = fabricCanvas.value!.getZoom();
    zoom *= 0.999 ** delta;
    
    if (zoom > 20) zoom = 20;
    if (zoom < 0.01) zoom = 0.01;
    
    fabricCanvas.value!.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
    
    // 更新状态
    editorStore.setZoom(zoom);
    
    opt.e.preventDefault();
    opt.e.stopPropagation();
  });
  
  // 监听画布平移事件
  fabricCanvas.value.on('mouse:down', (opt) => {
    if (opt.e.altKey) {
      fabricCanvas.value!.isDragging = true;
      fabricCanvas.value!.selection = false;
      fabricCanvas.value!.lastPosX = opt.e.clientX;
      fabricCanvas.value!.lastPosY = opt.e.clientY;
    }
  });
  
  fabricCanvas.value.on('mouse:move', (opt) => {
    if (fabricCanvas.value!.isDragging) {
      const e = opt.e;
      const vpt = fabricCanvas.value!.viewportTransform!;
      vpt[4] += e.clientX - fabricCanvas.value!.lastPosX;
      vpt[5] += e.clientY - fabricCanvas.value!.lastPosY;
      fabricCanvas.value!.requestRenderAll();
      fabricCanvas.value!.lastPosX = e.clientX;
      fabricCanvas.value!.lastPosY = e.clientY;
      
      // 更新状态
      editorStore.setPan(vpt[4], vpt[5]);
    }
  });
  
  fabricCanvas.value.on('mouse:up', () => {
    fabricCanvas.value!.isDragging = false;
    fabricCanvas.value!.selection = true;
  });
}

// 调整画布大小
function resizeCanvas() {
  if (!fabricCanvas.value) return;
  
  const container = document.querySelector('.canvas-wrapper');
  if (!container) return;
  
  const { width, height } = container.getBoundingClientRect();
  
  // 保持画布比例
  const aspectRatio = canvasWidth.value / canvasHeight.value;
  let newWidth = width;
  let newHeight = width / aspectRatio;
  
  if (newHeight > height) {
    newHeight = height;
    newWidth = height * aspectRatio;
  }
  
  fabricCanvas.value.setDimensions({
    width: newWidth,
    height: newHeight
  });
  
  fabricCanvas.value.requestRenderAll();
}

// 缩放控制
function zoomIn() {
  if (!fabricCanvas.value) return;
  
  let zoom = fabricCanvas.value.getZoom();
  zoom *= 1.1;
  
  if (zoom > 20) zoom = 20;
  
  fabricCanvas.value.setZoom(zoom);
  editorStore.setZoom(zoom);
}

function zoomOut() {
  if (!fabricCanvas.value) return;
  
  let zoom = fabricCanvas.value.getZoom();
  zoom *= 0.9;
  
  if (zoom < 0.01) zoom = 0.01;
  
  fabricCanvas.value.setZoom(zoom);
  editorStore.setZoom(zoom);
}

function resetZoom() {
  if (!fabricCanvas.value) return;
  
  fabricCanvas.value.setZoom(1);
  fabricCanvas.value.setViewportTransform([1, 0, 0, 1, 0, 0]);
  editorStore.setZoom(1);
  editorStore.setPan(0, 0);
}

// 绘制网格
function drawGrid() {
  if (!fabricCanvas.value || !showGrid.value) return;
  
  const gridSize = settingsStore.gridSize;
  const width = canvasWidth.value;
  const height = canvasHeight.value;
  
  const gridLines = [];
  
  // 绘制垂直线
  for (let i = 0; i <= width; i += gridSize) {
    gridLines.push(
      new fabric.Line([i, 0, i, height], {
        stroke: '#ccc',
        strokeWidth: 0.5,
        selectable: false,
        evented: false
      })
    );
  }
  
  // 绘制水平线
  for (let i = 0; i <= height; i += gridSize) {
    gridLines.push(
      new fabric.Line([0, i, width, i], {
        stroke: '#ccc',
        strokeWidth: 0.5,
        selectable: false,
        evented: false
      })
    );
  }
  
  // 添加到画布
  fabricCanvas.value.add(...gridLines);
}

// 暴露画布实例给父组件
defineExpose({
  fabricCanvas
});
</script>

<style scoped>
.svg-canvas-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.canvas-tools {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px;
  gap: 8px;
}

.zoom-level {
  font-size: 12px;
  color: var(--text-secondary);
  min-width: 40px;
  text-align: center;
}

.canvas-wrapper {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
}

canvas {
  border: 1px solid var(--border-color);
  box-shadow: 0 2px 8px var(--shadow-color);
}

.canvas-status {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px;
  gap: 16px;
  font-size: 12px;
}

/* 暗色主题样式 */
:deep(.dark-theme) canvas {
  border-color: var(--dark-border-color);
  box-shadow: 0 2px 8px var(--dark-shadow-color);
}
</style>